//
//  SNShareViewController.m
//  project
//
//  Created by 圆圆陈 on 2017/12/14.
//  Copyright © 2017年 黄建华. All rights reserved.
//

#import "SNShareViewController.h"
#import "TrackModel.h"
#import "UIImageView+WebCache.h"
#import "project-Swift.h"

@interface SNShareViewController ()
@property(nonatomic, strong) UIButton    *shareBtn;
@property(nonatomic, strong) UILabel     *distanceLabel;
@property(nonatomic, strong) UILabel     *timeLabel;
@property(nonatomic, strong) UILabel     *averageSpeedLabel;
@property(nonatomic, strong) UILabel     *fastSpeedLabel;
@property(nonatomic, strong) UILabel     *averagePaceLabel;
@property(nonatomic, strong) UILabel     *calLabel;
@property(nonatomic, strong) UIImageView *mapImageView;
@property(nonatomic, strong) UIButton    *shareStravaButton;
@property(nonatomic, strong) NSArray     *stravaShareArray;

@end

@implementation SNShareViewController
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self setInfoWithModel:self.model];
}

- (void)stravaShareResult1
{
    NSLog(@"strava 成功>>>");
    SN_PublicClass.result = @"1";
}

- (void)stravaShareResult2
{
    NSLog(@"strava 失败>>>");
    SN_PublicClass.result = @"0";
    SN_PublicClass.resultInfo = @"Your activity is still being processed.";
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(stravaShareFinish) name:@"stravaShareFinish" object:nil];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(stravaShareResult1) name:@"stravaShareResult1" object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(stravaShareResult2) name:@"stravaShareResult2" object:nil];

    UIButton *backBtn = [[UIButton alloc]initWithFrame:CGRectMake(10, 20+FitSimpleIpx(0, 20), 44, 44)];
    [backBtn setImageNormal:@"返回1"];
    [backBtn addTouchUpTarget:self action:@selector(backToLastVC)];
    [self.view addSubview:backBtn];
    
    _shareBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [_shareBtn setImageNormal:@"分享(1)"];
    _shareBtn.frame = CGRectMake(HHHWIDTH - 5 -44, 20+FitSimpleIpx(0, 20) +1, 44, 44);
    [_shareBtn addTouchUpTarget:self action:@selector(shareBtnClick)];
    [self.view addSubview:_shareBtn];
    
    _shareStravaButton       = [UIButton buttonWithType:UIButtonTypeCustom];
    _shareStravaButton.frame = CGRectMake(_shareBtn.left - 135, 20+FitSimpleIpx(0, 20) +2, 130, 40);
    [_shareStravaButton addTouchUpTarget:self action:@selector(shareStravaClick)];
    [_shareStravaButton setTitleColor:SNCOLORBLACK forState:UIControlStateNormal];
    [_shareStravaButton setTitleColor:SNCOLORGRAY forState:UIControlStateHighlighted];
    [_shareStravaButton setImage:[UIImage imageNamed:@"stravaShare"] forState:UIControlStateNormal];
    [_shareStravaButton setContentHorizontalAlignment:UIControlContentHorizontalAlignmentRight];
    _shareStravaButton.layer.cornerRadius = 4.0;
    [self.view addSubview:_shareStravaButton];
    
    SN_PublicClass.trackSubModel = _model;
    
    if (_model.trackArray.count == 0) {
        _shareStravaButton.hidden = YES;
    }
    else
    {
    _shareStravaButton.hidden = NO;
        if (_model.shareStrava) {
//    [_shareStravaButton setTitle:[NSString stringWithFormat:@"%@:Strava",SN_Text(@"已提交")] forState:UIControlStateNormal];
        }
        else
        {
//    [_shareStravaButton setTitle:[NSString stringWithFormat:@"%@:Strava",SN_Text(@"未提交")] forState:UIControlStateNormal];
        }
    }
    
    UILabel *shareLabel = [[UILabel alloc]initWithFrame:CGRectMake(HHHWIDTH-10-40-100-20, 32+FitSimpleIpx(0, 20), 100, 20)];
    shareLabel.text      = HHH_Text(@"分享给好友");
    shareLabel.textColor = [UIColor blackColor];
    shareLabel.font      = [UIFont fontWithName:@"PingFang" size:10];
    //[self.view addSubview:shareLabel];
    
    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"position"];
    animation.duration            = 1.0;
    animation.repeatCount         = HUGE_VALF;
    animation.autoreverses        = YES;
    animation.beginTime           = CACurrentMediaTime();
    animation.timingFunction      = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    animation.removedOnCompletion = NO;
    animation.fillMode            = kCAFillModeForwards;
    animation.fromValue           = [NSValue valueWithCGPoint:CGPointMake(HHHWIDTH-10-44-75, 32+FitSimpleIpx(0, 20)+10)];
    animation.toValue             = [NSValue valueWithCGPoint:CGPointMake(HHHWIDTH-10-44-25, 32+FitSimpleIpx(0, 20)+10)];
    [shareLabel.layer addAnimation:animation forKey:@"move-layer"];
    
    UIView *line = [[UIView alloc]initWithFrame:CGRectMake(0, backBtn.bottom, HHHWIDTH, 3)];
    [self.view addSubview:line];
    line.backgroundColor = SNCOLORSEPRATE;
    
    NSArray *arrOne   = @[HHH_Text(@"总里程"), HHH_Text(@"总耗时")];
    NSArray *arrTwo   = @[HHH_Text(@"平均时速"), HHH_Text(@"最快时速"), HHH_Text(@"平均配速"), HHH_Text(@"卡路里燃烧")];
    NSArray *imageArr = @[@"平均时速", @"最快时速", @"平均配速", @"卡路里"];
    CGFloat height    = HHHHEIGHT-HHHWIDTH-64-FitSimpleIpx(0, 20)-3-3-10;
    for (int i = 0; i < 6; i++) {
        CGFloat gapY = ((i-2)/2)*height/8;
        if (i < 2) {
            if (i == 1) {
                _distanceLabel               = [[UILabel alloc]initWithFrame:CGRectMake(0, line.bottom, HHHWIDTH/2, height/4)];
                _distanceLabel.font          = SNFONT(FitFont(45));
                _distanceLabel.textAlignment = NSTextAlignmentCenter;
                [self.view addSubview:_distanceLabel];
            } else {
                _timeLabel               = [[UILabel alloc]initWithFrame:CGRectMake(HHHWIDTH/2, line.bottom, HHHWIDTH/2, height/4)];
                _timeLabel.font          = SNFONT(FitFont(45));
                _timeLabel.textAlignment = NSTextAlignmentCenter;
                [self.view addSubview:_timeLabel];
            }
            UILabel *titleOne = [[UILabel alloc]initWithFrame:CGRectMake(HHHWIDTH/2*i, _timeLabel.bottom, HHHWIDTH/2, height/4)];
            titleOne.text          = arrOne[i];
            titleOne.textAlignment = NSTextAlignmentCenter;
            titleOne.font          = SNFONTMIN(FitFont(30));
            titleOne.textColor     = UIColorRGB(56, 59, 59);
            [self.view addSubview:titleOne];
        } else {
            UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(FitW(20)+HHHWIDTH/2*(i%2), line.bottom+((height/8-FitW(40))/2)+height*5/8+gapY*2, FitW(40), FitW(40))];
            imageView.image = UIImageNamed(imageArr[i-2]);
            [self.view addSubview:imageView];
            
            UILabel *titleTwo = [[UILabel alloc]initWithFrame:CGRectMake(FitW(60)+HHHWIDTH/2*(i%2), line.bottom+height*5/8+gapY*2, HHHWIDTH/2-FitW(60), height/8)];
            titleTwo.text          = arrTwo[i-2];
            titleTwo.textAlignment = NSTextAlignmentLeft;
            titleTwo.font          = SNFONTMIN(FitFont(15));
            titleTwo.textColor     = UIColorRGB(92, 93, 94);
            titleTwo.numberOfLines = 0;
            NSDictionary *attribute1 = @{NSFontAttributeName: titleTwo.font};
            //计算实际frame大小，并将label的frame变成实际大小
            CGSize labelsize1 = [titleTwo.text boundingRectWithSize:CGSizeMake(HHHWIDTH/2-FitW(60), MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:attribute1 context:nil].size;
            titleTwo.frame = CGRectMake(FitW(60)+HHHWIDTH/2*(i%2), line.bottom+height*5/8+gapY*2, labelsize1.width, labelsize1.height);
            [self.view addSubview:titleTwo];
            
            if (i == 2) {
                _averageSpeedLabel               = [[UILabel alloc]initWithFrame:CGRectMake(HHHWIDTH/2*(i%2), line.bottom+height/2+gapY, HHHWIDTH/2, height/8)];
                _averageSpeedLabel.font          = SNFONT(FitFont(24));
                _averageSpeedLabel.textAlignment = NSTextAlignmentCenter;
                [self.view addSubview:_averageSpeedLabel];
            } else if (i == 3) {
                _fastSpeedLabel               = [[UILabel alloc]initWithFrame:CGRectMake(HHHWIDTH/2*(i%2), line.bottom+height/2+gapY, HHHWIDTH/2, height/8)];
                _fastSpeedLabel.textAlignment = NSTextAlignmentCenter;
                _fastSpeedLabel.font          = SNFONT(FitFont(24));
                [self.view addSubview:_fastSpeedLabel];
            } else if (i == 4) {
                _averagePaceLabel               = [[UILabel alloc]initWithFrame:CGRectMake(HHHWIDTH/2*(i%2), line.bottom+height/2+gapY*2, HHHWIDTH/2, height/8)];
                _averagePaceLabel.textAlignment = NSTextAlignmentCenter;
                _averagePaceLabel.font          = SNFONT(FitFont(24));
                [self.view addSubview:_averagePaceLabel];
            } else {
                _calLabel               = [[UILabel alloc]initWithFrame:CGRectMake(HHHWIDTH/2*(i%2), line.bottom+height/2+gapY*2, HHHWIDTH/2, height/8)];
                _calLabel.font          = SNFONT(FitFont(24));
                _calLabel.textAlignment = NSTextAlignmentCenter;
                [self.view addSubview:_calLabel];
            }
        }
    }
    
    UIView *lineT = [[UIView alloc]initWithFrame:CGRectMake(0, line.bottom+height+10, HHHWIDTH, 3)];
    [self.view addSubview:lineT];
    lineT.backgroundColor = SNCOLORGRAY;
    
    _mapImageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, HHHHEIGHT-HHHWIDTH, HHHWIDTH, HHHWIDTH)];
    [self.view addSubview:_mapImageView];
}

- (void)backToLastVC {
    [self.navigationController popViewControllerAnimated:YES];
}

//GPX文件写入
-(void)writeStravaFile
{
    NSLog(@"strava share dic >>>>%@",_model.trackArray);
    if (_model.trackArray.count == 0) {
        return;
    }
    

    NSMutableString *stravaString = [NSMutableString string];
    [stravaString appendString:@"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"];
    [stravaString appendString:@"<gpx creator=\"StravaGPX iPhone\" version=\"1.1\" xmlns=\"http://www.topografix.com/GPX/1/1\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://www.topografix.com/GPX/1/1 http://www.topografix.com/GPX/1/1/gpx.xsd\">\n"];
    [stravaString appendString:@"<metadata>\n"];
    
    NSDate *startTime = [NSDate dateByString:_model.startTime];
    NSDate *date = startTime; // 获得时间对象
    NSTimeZone *zone = [NSTimeZone systemTimeZone]; // 获得系统的时区
    NSTimeInterval time = [zone secondsFromGMTForDate:date];// 以秒为单位返回当前时间与系统格林尼治时间的差
    NSDate *dateNow = [date dateByAddingTimeInterval:-time];// 然后把差的时间加

    NSString *s1 = [dateNow dateToDayString];
    NSString *s2 = [dateNow dateToTimeString];
    NSString *metadataTime = [NSString stringWithFormat:@"<time>%@T%@Z</time>\n",s1,s2];
    [stravaString appendString:metadataTime];
    
    [stravaString appendString:[NSString stringWithFormat:@"</metadata>\n<trk>\n<name>GetFitPro Walk</name>\n<type>9</type>\n<trkseg>\n"]];
    // 数据>>>>
    
    for (NSDictionary *dic in _model.trackArray) {
          NSMutableString *oneString = [NSMutableString string];
        [oneString appendString:[NSString stringWithFormat:@"<trkpt lat=\"%@\" lon=\"%@\">\n",dic[@"lat"],dic[@"lon"]]];
        [oneString appendString:[NSString stringWithFormat:@"<ele>%@</ele>\n",dic[@"ele"]]];
        NSString *timeString = dic[@"time"];

        // 日期格式化类
        NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
        fmt.dateFormat = @"yyyy-MM-dd HH:mm:ss";
        NSDate *date = [fmt dateFromString:timeString];
        NSLog(@"date>>>>>>%@",date);
        
        NSString *s1 = [date utcWithDate:date];
        NSLog(@"s1>>>>>>%@",s1);
        NSArray *timeArray = [s1 componentsSeparatedByString:@" "];
        [oneString appendString:[NSString stringWithFormat:@"<time>%@T%@Z</time>\n",[timeArray firstObject],[timeArray lastObject]]];
        [oneString appendString:@"</trkpt>\n"];
        [stravaString appendString:oneString];
    }
    
    [stravaString appendString:@"</trkseg>"];
    [stravaString appendString:@"</trk>"];
    [stravaString appendString:@"</gpx>"];
    [stravaString appendString:@"\n"];
    
//    NSLog(@"stravaString>>>>>%@",stravaString);
    //创建文件管理器
    NSFileManager *fileManager = [NSFileManager defaultManager];
    //获取路径
    //参数NSDocumentDirectory要获取那种路径
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];//去处需要的路径
    //更改到待操作的目录下
    [fileManager changeCurrentDirectoryPath:[documentsDirectory stringByExpandingTildeInPath]];
    //创建文件fileName文件名称，contents文件的内容，如果开始没有内容可以设置为nil，attributes文件的属性，初始为nil
    //获取文件路径
    [fileManager removeItemAtPath:@"test.gpx" error:nil];
    NSString *path = [documentsDirectory stringByAppendingPathComponent:@"test.gpx"];
    //创建数据缓冲
    NSMutableData *writer = [[NSMutableData alloc] init];
    //将字符串添加到缓冲中
    [writer appendData:[stravaString dataUsingEncoding:NSUTF8StringEncoding]];
    //将其他数据添加到缓冲中
    //将缓冲的数据写入到文件中
    BOOL ok = [writer writeToFile:path atomically:YES];
    if (ok) {
        NSLog(@"strava文件写入成功");
        SN_PublicClass.stravaPathString = path;
//        NSString *pathString = [[NSBundle mainBundle]pathForResource:@"test" ofType:@"gpx"];
//        SN_PublicClass.stravaPathString = pathString;
    }
    else
    {
        NSLog(@"strava文件写入失败");
    }
    
    NSLog(@"读取写入的文件内容>>>>  %@",[self readFile]);
}

- (void)stravaShareFinish
{
    NSLog(@"result >>>>%@ 提示:%@",SN_PublicClass.result,SN_PublicClass.resultInfo);
    
    if (SN_PublicClass.result.intValue == 1) {
         _model.shareStrava = YES;
        NSString *string = @"";
        if ([SN_PublicClass.resultInfo isEqualToString:@"Your activity is still being processed."]) {
            string = @"您的运动已经提交到Strava,请查看!";
        }
        else
        {
            string = SN_PublicClass.resultInfo;
        }
        NSString *info = [NSString stringWithFormat:@"%@:%@",SN_Text(@"已提交"),SN_Text(string)];
        SHOWMBProgressHUD(nil, info, nil, nil, 2.0);
    }
    else
    {
        _model.shareStrava = YES;
        NSString *info = [NSString stringWithFormat:@"%@:%@",SN_Text(@"错误!"),SN_Text(@"可能之前已经提交过")];
         SHOWMBProgressHUD(nil, info, nil, nil, 2.0);
    }

    [_model updateToDB];
    if (_model.shareStrava) {
//        [_shareStravaButton setTitle:[NSString stringWithFormat:@"%@:Strava",SN_Text(@"已提交")] forState:UIControlStateNormal];
    }
    else
    {
//        [_shareStravaButton setTitle:[NSString stringWithFormat:@"%@:Strava",SN_Text(@"未提交")] forState:UIControlStateNormal];
    }

}

-(NSString *)readFile
{
    //创建文件管理器
    NSFileManager *fileManager = [NSFileManager defaultManager];
    //获取路径
    //参数NSDocumentDirectory要获取那种路径
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];//去处需要的路径
    //更改到待操作的目录下
    [fileManager changeCurrentDirectoryPath:[documentsDirectory stringByExpandingTildeInPath]];
    //获取文件路径
    NSString *path = [documentsDirectory stringByAppendingPathComponent:@"test.gpx"];
    NSData *reader = [NSData dataWithContentsOfFile:path];
    return [[NSString alloc] initWithData:reader
                                 encoding:NSUTF8StringEncoding];
}

// strava
- (void)shareStravaClick {
    // 分享
    SHOWMBProgressHUD(SN_Text(@"请等待..."), nil, nil, NO, 5.0);
    if (!SN_PublicClass.showStravaToken) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:SN_Text(@"Strava")
                                                        message:SN_Text(@"Strava:未授权,请授权!") delegate:self
                                              cancelButtonTitle:nil
                                              otherButtonTitles:SN_Text(@"取消"), SN_Text(@"确定"), nil];
        [[UIView appearance] setTintColor:UIColorRGB(72, 72, 72)];
        [alert show];
    }
    else
    {
        [self writeStravaFile];
        SN_PublicClass.shareDescription = [NSString stringWithFormat:@"%@",_model.address];
        SNStravaShare *stravaShare = [[SNStravaShare alloc] init];
    }
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 1) {
        [SN_PublicClass cleanCacheAndCookie];
        SNStravaVc *vc = [[SNStravaVc alloc] init];
        CustomTabBar *tabBar = (CustomTabBar *)self.tabBarController;
        [tabBar hiddenTheTabBarView];
        [self.navigationController pushViewController:vc animated:YES];
    }
}

- (void)shareBtnClick {
    UIGraphicsBeginImageContext(CGSizeMake(screenWidth, screenHeight));
    
    [[UIApplication sharedApplication].delegate.window.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    NSMutableArray *items = [[NSMutableArray alloc] init];
    [items addObject:image];
    
    UIActivityViewController *activityViewController = [[UIActivityViewController alloc] initWithActivityItems:items applicationActivities:nil];
    NSMutableArray           *excludedActivityTypes  = [NSMutableArray arrayWithArray:@[
                                                                                        UIActivityTypeMessage, UIActivityTypeMail, UIActivityTypePrint, UIActivityTypeCopyToPasteboard, UIActivityTypeAssignToContact, UIActivityTypeSaveToCameraRoll, UIActivityTypeAddToReadingList, UIActivityTypePostToFlickr, UIActivityTypePostToVimeo, UIActivityTypePostToTencentWeibo, UIActivityTypeAirDrop,
                                                                                        UIActivityTypeOpenInIBooks]];
    activityViewController.excludedActivityTypes = excludedActivityTypes;
    
    [self presentViewController:activityViewController animated:YES completion:nil];
    activityViewController.completionWithItemsHandler = ^(UIActivityType __nullable activityType, BOOL completed, NSArray *__nullable returnedItems, NSError *__nullable activityError){
    };
}

- (void)setInfoWithModel:(TrackModel *)model {
    _distanceLabel.text     = SN_USER.isMetricSystem ? [NSString stringWithFormat:@"%.2fmile", roundf(model.totalDistances*0.0006214*100)/100] : [NSString stringWithFormat:@"%.2fkm", model.totalDistances*1.0/1000];
    _timeLabel.text         = [NSString stringWithFormat:@"%02ld:%02ld:%02ld", model.sportTotalTime/3600, (model.sportTotalTime%3600)/60, model.sportTotalTime%60];
    _averageSpeedLabel.text = SN_USER.isMetricSystem ? [NSString stringWithFormat:@"%.1fmile/h", model.averageSpeed/1000*3600*0.6213712] : [NSString stringWithFormat:@"%.1fkm/h", model.averageSpeed/1000*3600];
    _fastSpeedLabel.text    = SN_USER.isMetricSystem ? [NSString stringWithFormat:@"%.1fmile/h", model.maxSpeed/1000*3600*0.6213712] : [NSString stringWithFormat:@"%.2fkm/h", model.maxSpeed/1000*3600];
    _calLabel.text          = [NSString stringWithFormat:@"%.2fkcal", SN_USER.weight*model.totalDistances*1.0/1000*1.036];
    _averagePaceLabel.text  = [NSString stringWithFormat:@"%02ld'%02ld", model.averagePace/60, model.averagePace%60];
    NSString *path_document = NSHomeDirectory();
    NSString *imagePath     = [path_document stringByAppendingString:model.imagePath];
    //_mapImageView.image = [UIImage imageWithPath:imagePath];
    [_mapImageView sd_setImageWithURL:[NSURL URLWithString:model.imagePath]];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
